/*
 * Async Treeview 0.1 - Lazy-loading extension for Treeview
 * 
 * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
 *
 * Copyright (c) 2007 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 *
 */

;(function($) {

function load(settings, root, child, container) {
	function createNode(parent) {
		var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent);
		if (this.classes) {
			current.children("span").addClass(this.classes);
                        $('.drg').draggable({
//                        cursor: 'move',          // sets the cursor apperance
//                        revert: 'valid',       // makes the item to return if it isn't placed into droppable
//                        revertDuration: 0,     // duration while the item returns to its place
//                        opacity: 0.35            // opacity while the element is dragged
                            revert:  function(dropped) {
                               var dropped = dropped && dropped[0].id == "dp";
                               
                               return !dropped;
                            } 
                        }).each(function() {
                            
                            var top = $(this).position().top;
                            var left = $(this).position().left;
                            $(this).data('orgTop', top);
                            $(this).data('orgLeft', left);
                        });
                        var initDatasource=null;
                        $('#newQueryDrop').droppable({
                        accept: 'span.drg',            // accept only span contents with class 'drg'
                        activeClass: 'drp',           // add class "drp" while an accepted item is dragged
                        drop: function(event, ui) {
                        	initDatasource=ui.draggable.parents('li').last().attr('id');
                            var text = ui.draggable.parent().attr('id');
                            var criteriaValue = "DRAGED_ELEMENT_NEW_QUERY";
                            ui.draggable.mouseup(function () {
                                var top = ui.draggable.data('orgTop');
                                var left = ui.draggable.data('orgLeft');
                                
                                ui.position = {top: top, left: left};
                            });
                            $.get('controller',{criteria:criteriaValue,dragElement:text},function(responseText) { 
                                    //alert("New Query Successfully");
                                    initQueryTree();
                                   
                            });
                          $("#initDataSourceValue").val(initDatasource);
                            }
                        });
                  
                        $('#valueSubmitDrop').droppable({
                        accept: 'span.drg',            // accept only span contents with class 'drg'
                        activeClass: 'drp',           // add class "drp" while an accepted item is dragged
                        drop: function(event, ui) {
                            var text = ui.draggable.parent().attr('id');
                            //get datasource of node eg: DataSource: test2
                            var lastParent=ui.draggable.parents('li').last().attr('id');
                            $("#datasource").val(lastParent);
                            $("#currentDataSourceValue").val(lastParent);
                            var criteriaValue = "DRAGED_ELEMENT_VALUE";
                            $.get('controller',{criteria:criteriaValue,dragElement:text},function(responseText) {
                                if(responseText == "exception")
                                {
                                    alert("Please Specify Your Output!");
                                }
                                else
                                {
                                    var hashCount = responseText.match(/#/g);
                                    
                                    if((hashCount.length) > 1)
                                    {
                                        isAlreadyMerged = true;
                                        var firstIndexOfHash = responseText.indexOf("#");
                                        var lastIndexOfHash = responseText.lastIndexOf("#");
                                        
                                        $('#leafNode').val(responseText.substring(firstIndexOfHash + 1, lastIndexOfHash));
                                        
                                        var jsMessage = responseText.substring(lastIndexOfHash + 1,responseText.length);
                                        
                                        //alert("Merge Message = "+jsMessage);
                                        
                                        $('#merge').html(jsMessage);
                                        
                                        $( "#searchValueLeaf-form" ).dialog( "open" );
                                    }
                                    else
                                    {
                                        $('#merge').empty();
                                        
                                        // check if second dragged node in value is non-mergable
                                        if((count % 2) == 1)
                                        {
                                            isNonMergable = true;                                        
                                        }
//                                        if((count>4)&&((count % 2) == 1))
//                                        {
//                                            alert("isFinalNonMergable");
//                                            isFinalNonMergable = true;
//                                        }    
                                        
                                        var indexOfHash = responseText.indexOf("#");

                                        if(responseText.substring(0, indexOfHash) == "OPEN_SEARCH_VALUE_LEAF_FORM")
                                        {
                                            $('#leafNode').val(responseText.substring(indexOfHash + 1, responseText.length));
                                            $( "#searchValueLeaf-form" ).dialog( "open" );

                                        }
                                        else if(responseText.substring(0, indexOfHash) == "OPEN_SEARCH_VALUE_NON_LEAF_FORM")
                                        {
                                            $("#nonLeafNode").val(responseText.substring(indexOfHash + 1, responseText.length));
                                            $( "#searchValueNonLeaf-form" ).dialog( "open" );                             
                                        }
                                    }
                                }
                            });
                            }
                        });
              
                        $('#drop #sw').click(function(){
                            $('#drag .drg').slideDown(1000);
                        });
		}
		if (this.expanded) {
			current.addClass("open");
		}
		if (this.hasChildren || this.children && this.children.length) {
			var branch = $("<ul/>").appendTo(current);
			if (this.hasChildren) {
				current.addClass("hasChildren");
				createNode.call({
					classes: "placeholder",
					text: "&nbsp;",
					children:[]
				}, branch);
			}
			if (this.children && this.children.length) {
				$.each(this.children, createNode, [branch])
			}
		}
	}
	$.ajax($.extend(true, {
		url: settings.url,
		dataType: "json",
		data: {
			root: root
		},
		success: function(response) {
			child.empty();
			$.each(response, createNode, [child]);
	        $(container).treeview({add: child});
	    }
	}, settings.ajax));
	/*
	$.getJSON(settings.url, {root: root}, function(response) {
		function createNode(parent) {
			var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent);
			if (this.classes) {
				current.children("span").addClass(this.classes);
			}
			if (this.expanded) {
				current.addClass("open");
			}
			if (this.hasChildren || this.children && this.children.length) {
				var branch = $("<ul/>").appendTo(current);
				if (this.hasChildren) {
					current.addClass("hasChildren");
					createNode.call({
						classes: "placeholder",
						text: "&nbsp;",
						children:[]
					}, branch);
				}
				if (this.children && this.children.length) {
					$.each(this.children, createNode, [branch])
				}
			}
		}
		child.empty();
		$.each(response, createNode, [child]);
        $(container).treeview({add: child});
    });
    */
}

var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
	if (!settings.url) {
		return proxied.apply(this, arguments);
	}
	var container = this;
	if (!container.children().size())
		load(settings, "source", this, container);
	var userToggle = settings.toggle;
	return proxied.call(this, $.extend({}, settings, {
		collapsed: true,
		toggle: function() {
			var $this = $(this);
			if ($this.hasClass("hasChildren")) {
				var childList = $this.removeClass("hasChildren").find("ul");
				load(settings, this.id, childList, container);
			}
			if (userToggle) {
				userToggle.apply(this, arguments);
			}
		}
	}));
};

})(jQuery);